// map.js
// Fri 19 Mar 2010 01:42:05 PM EET

/* 
Initialization and simple manipulation functions for GeoTree demo.

Copyright (c) 2010 Artem Dudarev
License: Apache 2.0
*/

var map;
var points_data;
var markersArray = [];

function PointToTile(point,z){
    var currentProjection = G_NORMAL_MAP.getProjection();
    var tileCoordinate = new GPoint();
    var tilePoint = new GPoint();
    tilePoint = currentProjection.fromLatLngToPixel(point, z);
    tileCoordinate.x = Math.floor(tilePoint.x / 256);
    tileCoordinate.y = Math.floor(tilePoint.y / 256);
    return tileCoordinate;
}

function updateCenterInfo(){
    var z =  map.getZoom();
    var centerTile = PointToTile(map.getCenter(),z);
    var center_tile_str =  ' ' + centerTile.x + ',' + centerTile.y + ',' + z;
    $('#center_tile_info').text(center_tile_str);
}

function updateGeoTreeInfo(){
    $.get("/geo_tree_info",
        function (data) { 
            $('#geo_tree_info').html(data);
        }
    );
}

function sendPoint(latlng,z,importance,update_one){
    $.post("/insert_point", {
        lat: latlng.y,
        lng: latlng.x,
        z: z,
        importance: importance,
        update_one: update_one
        },
        function (data) { 
            $('#geo_tree_info').html(data);
        }
    );
}

function updateMap(){
    loadPoints();
}

function createMarker(latlng,i) {
    var marker = new GMarker(latlng,{draggable:true});
    marker.value = i;
    GEvent.addListener(marker, 'dblclick', function() { 
            removePoint(points_data[i]['key_name']);
            map.removeOverlay(marker);
            }); 
    return marker;
}

function removePoint(key_name){
    url = '/remove_point';
    $.get(url, {'key_name':key_name}, function(data){
            });
    updateGeoTreeInfo();
}

// Load JSON of all points in tiles (3x3 tiles around center tile)
function loadPoints(){
    map.clearOverlays();

    z = map.getZoom();
    centerTile = PointToTile(map.getCenter(),z);
    center =  centerTile.x + ',' + centerTile.y + ',' + z;
    
    url = '/t/?c=' + center;
    $.ajax({ url: url, success: function(data){
            markersArray = []
            points_data = eval(data);
            for(var i=0; i<points_data.length; i++){
                var lat = points_data[i]['coord'][0];
                var lon = points_data[i]['coord'][1];
                var marker = createMarker(new GLatLng(lat,lon),i);
                map.addOverlay(marker);
                markersArray.push(marker);
            }
    }});
}
// end of loadPoints()

// not to add the second marker when double-clicked
var just_clicked = false;
function clearJustClicked(){
    just_clicked = false;
}

function load() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map_canvas"));
        map.addControl(new GSmallZoomControl3D());
        map.addControl(new GMenuMapTypeControl());
        map.setCenter(new GLatLng(50, -98), 3);
        map.disableDoubleClickZoom();
        map.enableScrollWheelZoom();
    }

    GEvent.addListener(map, "dblclick", function(overlay, latlng) {
          return
    });

    GEvent.addListener(map, "click", function(overlay, latlng) {
        if (just_clicked){
            just_clicked = false;
            return;
        };
        just_clicked = true;
        map.addOverlay(createMarker(latlng),markersArray.length+1);
        z = map.getZoom();
        sendPoint(latlng,z,$("#importance").val(),$('#update_one').is(':checked'));
        // may add again after 250 ms
        just_clicked = setTimeout("clearJustClicked();",250);
    });

    GEvent.addListener(map, "move", function() {
        updateCenterInfo();
    });

    loadPoints();
    updateCenterInfo();
    updateGeoTreeInfo();

};
// end of load()
